package com.clementheliou.cheliou.dal.model.country.builder;

import org.springframework.util.Assert;

import com.clementheliou.cheliou.dal.dao.country.CountryDAO;
import com.clementheliou.cheliou.dal.model.country.Country;
import com.clementheliou.cheliou.util.builder.ObjectBuilder;

/**
 * Builder used to get {@link Country} instances for test purpose. It must only be used through one
 * of its static factory methods.
 * 
 * @author Clément HELIOU (clement.heliou@gmail.com)
 * @see {@link Country};
 * @see {@link ObjectBuilder}.
 * @since 1.0
 */
public class CountryBuilder extends ObjectBuilder<Country> {

	/**
	 * The {@link CountryDAO} to be used to persist the built instance if needed.
	 * 
	 * @author Clément HELIOU (clement.heliou@gmail.com)
	 * @since 1.0
	 */
	private final CountryDAO countryDAO;

	/**
	 * Private constructor from the {@link CountryDAO} to be used.
	 * 
	 * @author Clément HELIOU (clement.heliou@gmail.com)
	 * @param countryDAO the {@link CountryDAO} to be used.
	 * @since 1.0
	 */
	private CountryBuilder(CountryDAO countryDAO) {
		this.countryDAO = countryDAO;
	}

	/**
	 * Static factory method used to get a builder instance for a {@link Country} object that must
	 * be persistent. It's mostly used on data access layer's methods tests.
	 * 
	 * @author Clément HELIOU (clement.heliou@gmail.com)
	 * @param countryDAO the {@link CountryDAO} to be used.
	 * @return the builder instance to be used.
	 * @since 1.0
	 */
	public static CountryBuilder with(CountryDAO countryDAO) {
		return new CountryBuilder(countryDAO);
	}

	/**
	 * Creates a default {@link Country} instance, ready to be persisted.
	 * 
	 * @author Clément HELIOU (clement.heliou@gmail.com)
	 * @return the builder instance to be used.
	 * @since 1.0
	 */
	public CountryBuilder createDefaultCountry() {
		setInstance(createInstance());
		return this;
	}

	/**
	 * Persists the built {@link Country} instance then flush the current session.
	 * 
	 * @author Clément HELIOU (clement.heliou@gmail.com)
	 * @return the builder instance after this action.
	 * @since 1.0
	 */
	public CountryBuilder persistAndFlush() {
		Assert.notNull(countryDAO, "countryDAO must not be null at this time");

		countryDAO.saveEntity(getObject());
		countryDAO.flushSession();
		return this;
	}

	/**
	 * Creates a {@link Country} instance with default values. These ones have a functional sense.
	 * 
	 * @author Clément HELIOU (clement.heliou@gmail.com)
	 * @return the built instance.
	 * @since 1.0
	 */
	private Country createInstance() {
		final Country defaultCountry = new Country();
		defaultCountry.setLabelKey("labelKey");

		return defaultCountry;
	}
}
